`timescale 1ns / 1ps

/*
 * input: clock@1kHz
 * output: selection signal
 * 		data_sel: which digit shall be on the data bus (2'b00 to 2'b11)
 *		digit_en[i]: enable signal of digit displays (corresponds with data_sel)
 */
module display_half_driver(
	input clk_1khz,
	input [3:0] display_en,
	input [11:0] display_num,
	input [3:0] display_extra,
		
	output [7:0] decoded_num,
	output [3:0] digit_en_o
    );
    // 1kHz scanning speed
    wire clk_1khz;
    assign clk_1khz = clk_i;
    
    // selects which digit is on the bus
    reg [1:0] data_sel = 2'b00;
    
    // the digit on the bus, not decoded
    reg [2:0] num_bus = 8'b0;
	reg extra_bus = 1'b0;
	
	// enable signal
	reg [3:0] digit_en = 4'b0000;
	assign digit_en_o[0] = digit_en[0] & display_en[0];
	assign digit_en_o[1] = digit_en[1] & display_en[1];
	assign digit_en_o[2] = digit_en[2] & display_en[2];
	assign digit_en_o[3] = digit_en[3] & display_en[3];
    
    // decoder: decodes the digit
    decoder_3_seg DECODER(bus, extra_bus, decoded_num);

    always @(posedge clk_1khz) begin
		case (data_sel)
			2'b00: begin
				data_sel <= 2'b01;
				digit_en <= 4'b0001;
				num_bus <= display_num[2:0];
				extra_bus <= diplay_extra[0];
			end
			2'b01: begin
				data_sel <= 2'b10;
				digit_en <= 4'b0010;
				num_bus <= display_num[5:3];
				extra_bus <= diplay_extra[1];
			end
			2'b10: begin
				data_sel <= 2'b11;
				digit_en <= 4'b0100;
				num_bus <= display_num[8:6];
				extra_bus <= diplay_extra[2];
			end
			2'b11: begin
				data_sel <= 2'b00;
				digit_en <= 4'b1000;
				num_bus <= display_num[11:9];
				extra_bus <= diplay_extra[3];
			end
			default: begin
				data_sel <= 2'b01;
				digit_en <= 4'b0001;
				num_bus <= display_num[2:0];
				extra_bus <= diplay_extra[0];
			end
		endcase
    end
endmodule
